<template>
  <div class="login">
    <h1 class="title">超级市场后台管理系统</h1>
    <el-form
    ref="ruleFormRef"
    :model="formData"
    status-icon
    :rules="rules"
    label-width="120px"
    class="demo-ruleForm"
  >
    
    <el-form-item label="用户名" prop="username">
      <el-input v-model="formData.username" placeholder="请输入用户名" />
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >登录</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { useUserStore } from '@/store'
import { login } from '@/axios/api/user'
import { useRouter } from 'vue-router'

const store = useUserStore()
const router = useRouter()
console.log(useRouter())

const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码！'))
  }
  callback()
}

const formData = reactive({
  username: '',
  password: '',
})

const rules = reactive({
  password: [{ validator: validatePass, trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名！', trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  console.log(formEl)
  console.log(!formEl)
  if (!formEl) return
  formEl.validate((valid) => {
    console.log(valid)
    if (valid) {
      console.log('submit!', formData)
      login(formData).then((res: any) => {
        store.login(res)
        console.log(store)
        console.log(store.user)
        router.push('/')
      })
      
    } else {
      console.log('error submit!')
      return false
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>


<style scoped lang="scss">
  .title{
    position: absolute;
    top: 100px;
    color: white;
    text-align: center;
    width: 100%;
  }
  .login{
    background-color: cadetblue;
    height: 100%;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    .el-form{
      margin: auto;
      width: 60%;
      // margin-top: 200px;
      // margin-left: auto;
      // margin-right: auto;
      background-color: #fff;
      padding: 100px;
      border-radius: 10px;
      box-shadow: 0 0 10px rgba($color: #fff, $alpha: .5);
    }
  }
</style>